<template>
  <el-dialog v-if="load" :close-on-click-modal="false" :title="isPurchase ? '申请付款' : isPay ? '付款' : isLook ? '详情' : '编辑'" v-model="visible" align-center :z-index="2000"
    width="1360px" @close="handleClose">
    <el-form ref="formRef" :model="form" label-width="110px" :disabled="isLook" label-position="top">
      <div class="v-title mb-3">基础信息</div>
      <div class="grid grid-cols-4 gap-x-3">
        <el-form-item label="供应商">
          <el-input v-model="form.basic.supplier_name" placeholder="请输入" disabled />
        </el-form-item>
        <el-form-item label="供应商类型">
          <VSelect v-model="form.basic.purchase_type" placeholder="请选择" :options="options.purchase_type || []" filterable clearable disabled class="w-full" />
        </el-form-item>
        <el-form-item label="结算方式">
          <el-input v-model="form.basic.period_name" placeholder="请输入" disabled class="w-full" />
        </el-form-item>
        <el-form-item label="公司主体">
          <VSelect v-model="form.basic.company_id" placeholder="请选择" :options="options.company_id || []" filterable clearable
            :disabled="[1, 3].includes(form.basic.apply_payment_type)" class="w-full" @change="companyChange" />
        </el-form-item>
        <el-form-item label="交易方式">
          <VSelect v-model="form.basic.payment_type" placeholder="请选择" :options="options.payment_type || []" filterable clearable disabled class="w-full" />
        </el-form-item>
        <el-form-item label="支付账号" prop="basic.payment_account" :rules="[{ required: isPay && !isPurchase, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="form.basic.payment_account" placeholder="请选择" :options="options.payment_account || []" filterable clearable
            :disabled="form.basic.payment_status !== 4 || isPurchase" class="w-full" />
        </el-form-item>
        <el-form-item label="支付币种">
          <VSelect v-model="form.basic.payment_currency" placeholder="请选择" :options="options.currency || []" filterable clearable disabled class="w-full" />
        </el-form-item>
        <el-form-item label="收款人" prop="basic.collect_name" :rules="[{ required: form.basic.purchase_type!==1 && !isPay, message: '不能为空', trigger: 'blur' }]">
          <el-input v-model="form.basic.collect_name" placeholder="请输入" class="w-full" :disabled="isPay" />
        </el-form-item>
        <el-form-item label="收款账号" prop="basic.collect_account" :rules="[{ required: form.basic.purchase_type!==1 && !isPay, message: '不能为空', trigger: 'blur' }]">
          <el-input v-model="form.basic.collect_account" placeholder="请输入" class="w-full" :disabled="isPay" />
        </el-form-item>
        <el-form-item label="银行名称" prop="basic.collect_bank" :rules="[{ required: form.basic.purchase_type!==1 && !isPay, message: '不能为空', trigger: 'blur' }]">
          <el-input v-model="form.basic.collect_bank" placeholder="请输入" :disabled="isPay" />
        </el-form-item>
        <el-form-item label="支行名称" prop="basic.bank_address" :rules="[{ required: form.basic.purchase_type!==1 && !isPay, message: '不能为空', trigger: 'blur' }]">
          <el-input v-model="form.basic.bank_address" placeholder="请输入" :disabled="isPay" />
        </el-form-item>
        <el-form-item v-if="!isPurchase" label="申请人">
          <el-input v-model="form.basic.create_user" placeholder="请输入" disabled class="w-full" />
        </el-form-item>
        <el-form-item label="期望付款时间" prop="basic.except_payment_time" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <el-date-picker v-model="form.basic.except_payment_time" type="date" :disabled="isPay" :clearable="false" value-format="YYYY-MM-DD" placeholder="结束日期" class="w-full" @change="dateChange" />
        </el-form-item>
        <el-form-item label="付款项目" prop="basic.payment_item" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="form.basic.payment_item" placeholder="请选择" :options="options.payment_item" class="w-full" />
        </el-form-item>
        <template v-if="!isPurchase">
          <el-form-item label="付款单号">
            <el-link type="primary">{{ form.basic.payment_no }}</el-link>
          </el-form-item>
          <template v-if="isPay || isLook">
            <el-form-item label="付款金额">
              <el-input-number v-model="form.basic.apply_price" :controls="false" :min="0" :step="0.01" :precision="2" class="w-full" />
            </el-form-item>
          </template>
        </template>
        <el-form-item label="申请付款类型" prop="basic.apply_payment_type" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="form.basic.apply_payment_type" placeholder="请选择" :options="options.apply_payment_type" filterable :clearable="false" :disabled="isPay" class="w-full"
            @change="paymentTypeChange" />
        </el-form-item>
        <el-form-item label="付款方式" v-if="[1, 2, 3].includes(form.basic.apply_payment_type) && !isLook && !isPay && !isEdit">
          <VSelect v-model="form.apply_type" placeholder="请选择" :options="[{label: '比例付款', value: 1},{label: '手动付款', value: 2}]" :clearable="false" class="w-full"
            @change="applyTypeChange" />
        </el-form-item>
        <template v-if="[1,2, 3].includes(form.basic.apply_payment_type)&& !isLook && !isPay && form.apply_type === 1 && !isEdit">
          <!-- <el-form-item label="待申请付款金额" prop="basic.apply_total_price" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
            <el-input-number v-model="form.basic.apply_total_price" :controls="false" :disabled="true" :step="0.01" :precision="2" class="w-full" />
          </el-form-item> -->
          <el-form-item label="付款比例" prop="basic.apply_percent" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
            <VGroup class="w-full">
              <VSelect v-if="isOpt" v-model="apply_percent_value" placeholder="请选择" :options="[{label:'按剩余付款金额',value:1},{label:'按采购总金额',value:2}]" :clearable="false" :disabled="isPay" @change="handlePercent"/>
              <el-input-number v-model="form.basic.apply_percent" :controls="false" :disabled="isPay" :step="0.01" :precision="2"
                :min="1" :max="100" class="w-full" @change="percentChange">
              </el-input-number>
              <div class="v-group-item el-input-group__append">%</div>
            </VGroup>
          </el-form-item>
          <el-form-item label="申请付款总金额" prop="basic.apply_price" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
            <el-input-number v-model="form.basic.apply_price" :controls="false" disabled :step="0.01" :precision="2" class="w-full" />
          </el-form-item>
        </template>
        <el-form-item v-else label="申请付款总金额" prop="basic.apply_price" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <el-input-number v-model="form.basic.apply_price" :controls="false" disabled :step="0.01" :precision="2" class="w-full" />
        </el-form-item>
        <el-form-item label="申请货款总金额" prop="basic.apply_goods_price" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <el-input-number v-model="form.basic.apply_goods_price" :controls="false" disabled :step="0.01" :precision="2" class="w-full" />
        </el-form-item>
        <el-form-item label="申请下单前运费总金额" prop="basic.apply_before_tracking_price" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <el-input-number v-model="form.basic.apply_before_tracking_price" :controls="false" disabled :step="0.01" :precision="2" class="w-full" />
        </el-form-item>
        <el-form-item label="申请下单后运费总金额" prop="basic.apply_tracking_price" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <el-input-number v-model="form.basic.apply_tracking_price" :controls="false" :disabled="isPay || form.basic.apply_payment_type === 1" :step="0.01" :precision="2"
            class="w-full" @change="applyTrackingPriceChange" />
        </el-form-item>
        <el-form-item label="优惠">
          <el-input-number v-model="form.basic.discount_price" :controls="false" :step="0.01" :precision="2" placeholder="请输入" disabled class="w-full" />
        </el-form-item>
        <el-form-item label="售后">
          <el-input-number v-model="form.basic.after_sale_price" :controls="false" :disabled="isPay || form.basic.apply_payment_type === 2" :step="0.01" :precision="2"
            placeholder="请输入" class="w-full" @change="priceChange" />
        </el-form-item>
        <el-form-item label="折扣">
          <el-input-number v-model="form.basic.preferential_price" :controls="false" :disabled="isPay || form.basic.apply_payment_type === 2" :step="0.01" :precision="2"
            placeholder="请输入" class="w-full" @change="priceChange" />
        </el-form-item>
        <el-form-item label="飞书审核">
          <div class="flex items-center gap-3">
            <el-switch v-model="form.basic.is_feishu_audit" inline-prompt active-text="是" inactive-text="否" :active-value="2" :inactive-value="1" />
            <div class="text-green-600 text-xs">提示：启用后只能在飞书审核</div>
          </div>
        </el-form-item>
        <el-form-item label="对账金额" prop="basic.bill_price" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <el-input-number v-model="form.basic.bill_price" :controls="false" :min="0" :step="0.01" :precision="2" placeholder="请输入" class="w-full" />
        </el-form-item>
        <el-form-item label="对账月份" prop="basic.bill_month" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
          <el-input v-model="form.basic.bill_month" placeholder="请输入" class="w-full" />
        </el-form-item>
        <el-form-item label="备注" class="col-span-full">
          <el-input v-model="form.basic.remark" placeholder="请输入" type="textarea" :disabled="isPay" :autosize="{ minRows: 2, maxRows: 5 }" resize="none" />
        </el-form-item>
        <div class="col-span-full mb-2">
          <VUpload v-model="form.basic.attachment" title="采购附件" :disabled="isPay" multiple :types="['jpg', 'jpeg', 'png', 'xlsx', 'xml', 'pdf']">
            图片类型只能是jpg/png/jpeg/xml/xlsx/pdf，不超过5M
          </VUpload>
        </div>
        <div v-if="isPay || isLook" class="col-span-full">
          <VUpload v-model="form.basic.payment_voucher" paste title="付款凭证" class="col-span-full mb-2" />
        </div>
      </div>
      <div class="v-title mb-3 mt-2 flex">
        <div class="flex-1">采购单信息</div>
        <div>
          <VText title="申请付款总金额" :value="form.basic.apply_price" class="ml-auto" />
        </div>
      </div>
      <vxe-table ref="tableRef" :data="form.purchase" size="small" :max-height="560" :row-config="{height: 60}" :scroll-y="{enabled: true}">
        <vxe-column title="采购单号" :min-width="140" fixed="left">
          <template #default="{ row }">
            <el-link type='primary'>{{ row.purchase_no }}</el-link>
            <VText title="平台单号" :value="row.platform_order_no" />
          </template>
        </vxe-column>
        <vxe-column title="sku" field="sku" :min-width="100" fixed="left" />
        <vxe-column title="产品名称" field="sku_cn_title" :min-width="180">
          <template #default="{ row }">
            <VText :value="row.sku_cn_title" :line="2" />
          </template>
        </vxe-column>
        <vxe-column title="下单数量" field="purchase_num" :min-width="100" />
        <vxe-column title="下单金额" :min-width="100">
          <template #default="{ row }">
            <div><span class='text-gray-500'></span>{{ row.is_drawback === 2 ?
    row.total_purchase_price_tax :
    row.total_purchase_price }}</div>
          </template>
        </vxe-column>
        <vxe-column title="产品总金额" field="tracking_price" :min-width="80">
          <template #default="{ row }">
            <div><span class='text-gray-500'></span>{{ row.is_drawback === 2 ?
    row.total_price_tax :
    row.total_price }}</div>
          </template>
        </vxe-column>
        <vxe-column title="下单前运费" field="tracking_price" :min-width="80" />
        <vxe-column title="下单后运费" field="had_apply_tracking_price" :min-width="80" />
        <vxe-column title="优惠" field="discount_price" :min-width="80" />
        <vxe-column title="折扣" field="preferential_price" :min-width="80" />
        <vxe-column title="售后" field="after_sale_price" :min-width="80" />
        <vxe-column v-if="isPurchase" title="入库数量" field="inbound_num" :min-width="80" />
        <vxe-column title="入库仓库" field="destination_warehouse_name" :min-width="80" />
        <vxe-column title="入库金额" field="inbound_price" :min-width="80" />
        <vxe-column title="入库时间" field="inbound_time" :min-width="110">
          <template #default="{ row }">
            <VText :value="row.inbound_time" line="2" />
          </template>
        </vxe-column>
        <vxe-column v-if="isPurchase" title="库内退货数量" :min-width="110">
          <template #header>库内退货数量<br>库内退货金额</template>
          <template #default="{ row }">
            <div><span class='text-gray-500'>数量: </span>{{ row.return_num }}</div>
            <div><span class='text-gray-500'>金额: </span>{{ row.return_price }}</div>
          </template>
        </vxe-column>
        <vxe-column title="退款金额" field="refund_price" :min-width="80" />
        <vxe-column title="待申请付款金额" field="orign_wait_apply_price" :min-width="80" />
        <vxe-column title="已申请未付款金额" field="wait_payment_price" :min-width="80" />
        <vxe-column title="已申请未付款运费" field="wait_payment_tracking_price" :min-width="80" />
        <vxe-column title="已付金额" field="payment_price" :min-width="80" />
        <vxe-column title="申请货款金额" :min-width="90" fixed="right">
          <template #default="{ row }">
            <el-input-number v-if="isEdit" v-model="row.apply_goods_price" :controls="false" :disabled="form.basic.apply_payment_type === 2" :step="0.01"
              :precision="2" class="w-full" />
            <el-input-number v-else v-model="row.apply_goods_price" :controls="false" :disabled="isPay || form.basic.apply_payment_type === 2 || form.apply_type === 1" :step="0.01"
              :precision="2" class="w-full" />
          </template>
        </vxe-column>
        <vxe-column title="申请下单前运费金额" :min-width="90" fixed="right">
          <template #default="{ row }">
            <el-input-number v-model="row.apply_before_tracking_price" :controls="false" disabled :step="0.01" :precision="2" class="w-full" />
          </template>
        </vxe-column>
        <vxe-column title="申请下单后运费金额" :min-width="90" fixed="right">
          <template #default="{ row }">
            <el-input-number v-model="row.apply_tracking_price" :controls="false" :disabled="isPay || form.basic.apply_payment_type === 1" :step="0.01" :precision="2"
              class="w-full" />
          </template>
        </vxe-column>
        <vxe-column title="申请付款金额" :min-width="90" fixed="right">
          <template #default="{ row }">
            {{row.apply_price}}
          </template>
        </vxe-column>
        <vxe-column title="最后结算日期" field="start_payment_time" :min-width="100" fixed="right" />
        <vxe-column v-if="isPurchase" title="操作" :width="80" fixed="right">
          <template #default="{ rowIndex }">
            <el-button v-if="form.purchase.length > 1" type="text" @click="remove(rowIndex)">移除</el-button>
          </template>
        </vxe-column>
      </vxe-table>
    </el-form>
    <template v-if="isLook">
      <div class="v-title my-3">操作日志</div>
      <vxe-table :data="form.log" size="small">
        <vxe-column title="操作人" field="create_user"></vxe-column>
        <vxe-column title="操作类型" field="log_type"></vxe-column>
        <vxe-column title="详情" field="log_info" min-width="300"></vxe-column>
        <vxe-column title="操作时间" field="create_time"></vxe-column>
      </vxe-table>
    </template>
    <template #footer>
      <template v-if="isLook">
        <el-button @click="close">关 闭</el-button>
      </template>
      <template v-else-if="isPay">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loadings.pay" @click="pay(1)">付 款</el-button>
      </template>
      <template v-else>
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loadings[2]" @click="create(2)">确 定</el-button>
        <el-button type="primary" :loading="loadings[1]" @click="create(1)">提 交</el-button>
      </template>
    </template>
  </el-dialog>
</template>

<script setup>
import api from '../api'
import { ElMessage } from 'element-plus'
import XEUtils from 'xe-utils'
import { nextTick } from 'vue'

const props = defineProps({
  options: { type: Object, default: () => ({}) },
  isPurchase: Boolean,
})
const emit = defineEmits(['close', 'success'])

const load = ref(false)
const visible = ref(false)
const isLook = ref(false)
const isEdit = ref(false)
const isPay = ref(false)
let loadings = reactive({})

// 表单处理
const formRef = ref()
const form = ref({
  basic: { payment_voucher: [], attachment: [] },
  purchase: [],
})

const dateChange = val => {
  if(!form.value.purchase.map(d => d.inbound_time).filter(Boolean)?.length) {
    form.value.basic.bill_month = val.substring(0, 7)
  }
}

const remove = (rowIndex) => {
  form.value.purchase.splice(rowIndex, 1)
  form.value.basic.bill_month = form.value.purchase.reduce((acc, cur) => {
    const date = cur.inbound_time.substring(0, 7)
    return acc.includes(date) ? acc : acc.concat(date)
  },[]).join(',')
  priceChange()
}

// 申请付款类型 options
// const apply_payment_type = computed(() => {
//   if (!form.value.basic || !props.options.apply_payment_type) return []
//   return ![1].includes(form.value.basic.purchase_type) ? props.options.apply_payment_type.slice(0, 2) : props.options.apply_payment_type.slice(2)
// })

// 重置付款金额
const setPrice = () => {
  const reset = form.value.basic.apply_payment_type === 2
  if (reset) {
    form.value.basic.after_sale_price = 0
    form.value.basic.preferential_price = 0
  }
  form.value.purchase.forEach(d => {
    if (reset) {
      d.after_sale_price = 0
      d.preferential_price = 0
    }
  })
  resetPrice()
}

const resetPrice = () => {
  if (isPay.value || isLook.value || isEdit.value) return
  form.value.basic.apply_goods_price = form.value.basic.apply_payment_type === 2 ? 0 : form.value.basic.wait_apply_goods_price
  form.value.basic.apply_before_tracking_price = form.value.basic.apply_payment_type === 1 ? 0 : form.value.basic.wait_apply_before_tracking_price
  form.value.basic.apply_tracking_price = form.value.basic.apply_payment_type === 1 ? 0 : (form.value.basic.wait_apply_tracking_price??0)
  form.value.basic.discount_price = form.value.basic.wait_discount_price
  form.value.purchase.forEach(d => {
    d.apply_goods_price = form.value.basic.apply_payment_type === 2 ? 0 : d.wait_apply_goods_price
    d.apply_before_tracking_price = form.value.basic.apply_payment_type === 1 ? 0 : d.wait_apply_before_tracking_price
    d.apply_tracking_price = form.value.basic.apply_payment_type === 1 ? 0 : d.wait_apply_tracking_price
    d.discount_price = d.wait_discount_price
    d.apply_price = form.value.basic.apply_payment_type !=1?(Number(d?.wait_apply_price||0)+Number(d?.return_tracking_price||0)):Number(d?.apply_price||0)
  })
}

// 申请付款类型变化
const company_id = ref()
const paymentTypeChange = ({ value }) => {
  setPrice()
  percentChange()
  form.value.basic.company_id = value === 2 ? 2 : company_id.value
  companyChange()
}

// 付款方式变化
const applyTypeChange = () => {
  setPrice()
}

// 公司主体变化
const companyChange = () => {
  const { supplier_id, company_id } = form.value.basic
  api.getCollect({ supplier_id, company_id }).then(res => {
    form.value.basic = { ...form.value.basic, ...res.data }
  })
}

// 比例变化
const percentChange = () => {
  form.value.purchase = JSON.parse(JSON.stringify(originalPurchase.value));
  if(apply_percent_value.value==2){
    const { apply_percent } = form.value.basic;
    const percent = apply_percent / 100;
    form.value.purchase.forEach(d => {
      if (form.value.apply_type === 1 && form.value.basic.apply_payment_type !== 2) {
        d.apply_goods_price = round(d.origin_goods_price  * percent)
        d.apply_before_tracking_price =form.value.basic.apply_payment_type==1?0:round(d.origin_before_tracking_price  * percent)
        d.discount_price = round(d.origin_discount_price  * percent)
      }
      if(form.value.apply_type === 1 && form.value.basic.apply_payment_type == 2){
        d.apply_before_tracking_price =  round(d.origin_before_tracking_price  * percent)
        d.apply_goods_price = 0
        d.discount_price = round(d.origin_discount_price  * percent)
      }
    })
  }else{
      form.value.purchase.forEach(d => {
      if (form.value.apply_type === 1 && form.value.basic.apply_payment_type !== 2) {
      d.apply_goods_price = round(d.wait_apply_goods_price * (form.value.basic.apply_percent / 100))
      d.discount_price = round(d.wait_discount_price * (form.value.basic.apply_percent / 100))
      d.apply_before_tracking_price =form.value.basic.apply_payment_type==1?0:round(d.wait_apply_before_tracking_price * (form.value.basic.apply_percent / 100))
    }
    if(form.value.apply_type === 1 && form.value.basic.apply_payment_type == 2){
        d.apply_before_tracking_price = round(d.wait_apply_before_tracking_price  * (form.value.basic.apply_percent / 100))
        d.apply_goods_price = 0
        d.discount_price = round(d.wait_discount_price * (form.value.basic.apply_percent / 100))    
    }
  })
  }
}

// 总运费变化
// const applyTrackingPriceChange = val => {
//   const all = form.value.purchase.reduce((acc, cur) => acc += Math.max(cur.gross_weight_g || 0, cur.volume_g || 0), 0)
//   form.value.purchase.forEach(d => {
//     const ratio = round(Math.max(d.gross_weight_g || 0, d.volume_g || 0) / all, 6)
//     d.apply_tracking_price = round(form.value.basic.apply_tracking_price * ratio)
//   })
// }
const applyTrackingPriceChange = val => {
  const baseTrackingPrice = form.value.basic.apply_tracking_price;
  const all = form.value.purchase.reduce((acc, cur) => acc += Math.max(cur.gross_weight_g || 0, cur.volume_g || 0), 0)
  let accumulatedError = baseTrackingPrice;
  form.value.purchase.forEach((d, index) => {
    const ratio = round(Math.max(d.gross_weight_g || 0, d.volume_g || 0) / all, 6)
    if (index < form.value.purchase.length - 1) {
      const trackingPrice = round(baseTrackingPrice * ratio);
      d.apply_tracking_price = trackingPrice;
      accumulatedError -= trackingPrice;
    }else{
      d.apply_tracking_price = round(accumulatedError);
    }
  })
}

// 计算价格
// apply_payment_type 货款1 运费2 货款+运费3
// apply_type 比例付款1 手动付款 2
const round = (val, num = 2) => XEUtils.round(val, num)
const priceChange = () => {
  // 计算折扣和售后
  form.value.basic.discount_price = round(form.value.purchase.reduce((acc, cur) => acc + (Number(cur.discount_price) || 0), 0))
  form.value.purchase.forEach(d => {
    const ratio = round(d.apply_goods_price / form.value.basic.apply_goods_price, 6)
    d.after_sale_price = round(form.value.basic.after_sale_price * ratio)
    d.preferential_price = round(form.value.basic.preferential_price * ratio)
  })
  // 处理偏离值
  const { after_sale_price, preferential_price } = form.value.purchase.reduce((acc, cur) => {
    acc.after_sale_price += cur.after_sale_price
    acc.preferential_price += cur.preferential_price
    return acc
  }, { after_sale_price: 0, preferential_price: 0 })
  // 售后
  const afterSaleOffset = round(form.value.basic.after_sale_price - after_sale_price)
  if (afterSaleOffset) {
    form.value.purchase[form.value.purchase.length - 1].after_sale_price = round(form.value.purchase[form.value.purchase.length - 1].after_sale_price + afterSaleOffset)
  }
  // 折扣
  const preferentialOffset = round(form.value.basic.preferential_price - preferential_price)
  if (preferentialOffset) {
    form.value.purchase[form.value.purchase.length - 1].preferential_price = round(form.value.purchase[form.value.purchase.length - 1].preferential_price + preferentialOffset)
  }
}
// 单行申请付款变化
// 申请货款金额 apply_goods_price 申请下单前运费金额 apply_before_tracking_price 申请下单后运费金额 apply_tracking_price
// 优惠 discount_price  折扣 preferential_price 售后 after_sale_price
const rowApplyPrice = (data = form.value.purchase) => {
  form.value.basic.apply_goods_price = round(data.reduce((acc, cur) => acc += cur.apply_goods_price, 0))
  form.value.basic.apply_before_tracking_price = round(data.reduce((acc, cur) => acc += cur.apply_before_tracking_price, 0))
  form.value.basic.apply_tracking_price = round(data.reduce((acc, cur) => acc += cur.apply_tracking_price, 0))
  //todo
  form.value.basic.discount_price = round(data.reduce((acc, cur) => acc += cur.discount_price, 0))
  data.forEach(d => {
    d.apply_price = round(d.apply_goods_price + d.apply_before_tracking_price + d.apply_tracking_price - d.discount_price - d.preferential_price - d.after_sale_price)
    d.apply_price = form.value.basic.apply_payment_type !=1?(Number(d?.apply_price||0)+Number(d?.return_tracking_price||0)):Number(d?.apply_price||0)
  })
  form.value.basic.apply_price = round(data.reduce((acc, cur) => acc += cur.apply_price, 0))
}
const isInitialized = ref(false);
watch(
  () => form.value.purchase,
  (val) => {
    if (isPay.value || isLook.value || !isInitialized.value) return
    rowApplyPrice()
  },
  {
    deep: true
  }
)

//判断是否是采购单管理的申请付款
const isOpt = ref(false)
//付款比例选择
const apply_percent_value = ref(1)
const originalPurchase = ref([])
// 打开弹窗
const open = async (p_ids, option = {}) => {
  apply_percent_value.value = 1
  originalPurchase.value = []
  isInitialized.value = false
  isLook.value = option?.look
  isPay.value = option?.pay
  isEdit.value = option?.edit
  isOpt.value = Object.keys(option || {}).length === 0 ? true : false;
  if (!load.value) {
    load.value = true
    await 1
  }
  form.value = {
    basic: { payment_voucher: [] },
    purchase: [],
  }
  loadings = reactive({})
  formRef?.value?.resetFields()

  try {
    if (option?.bill) {
      const res = await api.billDetail({ cb_ids: p_ids })
      form.value = res.data
      form.value.basic.apply_payment_type = 3
    } else if (props.isPurchase) {
      const res = await api.selectDetail({ p_ids })
      form.value = res.data
    } else {
      const res = await api.detail({ p_id: p_ids[0] })
      form.value = res.data
    }

    company_id.value = form.value.basic.company_id
    form.value.basic.attachment = form.value.basic.attachment || []
    form.value.basic.payment_voucher = form.value.basic.payment_voucher || []
    form.value.basic.apply_total_price = form.value.basic.apply_total_price || 0
    form.value.basic.after_sale_price = form.value.basic.after_sale_price || 0
    form.value.basic.preferential_price = form.value.basic.preferential_price || 0
    form.value.basic.payment_item = form.value.basic.payment_item || (form.value.basic.purchase_type === 1 ? 1 : 2)
    // form.value.purchase = [...new Array(320).keys()].map(d => form.value.purchase[0])
    form.value.purchase.forEach(d => {
      d.discount_price = d.discount_price || 0
      d.apply_total_price = d.apply_total_price || 0
      d.after_sale_price = d.after_sale_price || 0
      d.preferential_price = d.preferential_price || 0
      d.apply_before_tracking_price = +d.apply_before_tracking_price || 0
      d.apply_tracking_price = +d.apply_tracking_price || 0
      d.apply_goods_price = +d.apply_goods_price || 0
    })
    form.value.apply_type = 1
    form.value.basic.apply_percent = 100
    form.value.basic.apply_payment_type = form.value.basic.apply_payment_type || (form.value.basic.purchase_type === 1 ? 3 : 1)
    resetPrice()
    form.value.purchase.forEach(d => {
    d.apply_price = round(d.apply_goods_price + d.apply_before_tracking_price + d.apply_tracking_price - d.discount_price - d.preferential_price - d.after_sale_price)
    d.apply_price = form.value.basic.apply_payment_type !=1?(Number(d?.apply_price||0)+Number(d?.return_tracking_price||0)):Number(d?.apply_price||0)
    })
    setTimeout(()=>{
      originalPurchase.value = JSON.parse(JSON.stringify(form.value.purchase));
      isInitialized.value = true
    },1000)
  } catch (error) {
    return
  }
  visible.value = true
}


const handlePercent = ({value})=>{
    percentChange()
}

// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}
// 提交
const create = async (is_submit) => {
  if (!await formRef?.value.validate()) return
  loadings[is_submit] = true
  form.value.basic.is_submit = is_submit
  api[props.isPurchase ? 'applyPayment' : 'edit'](form.value).then(res => {
    ElMessage.success('操作成功')
    emit('success')
    close()
  }).finally(() => {
    loadings[is_submit] = false
  })
}
// 付款
const pay = async () => {
  if (!await formRef?.value.validate()) return
  loadings.pay = true
  const { p_id, apply_price, payment_voucher, payment_account } = form.value.basic
  api.pay({ p_id, payment_price: apply_price, payment_voucher, payment_account }).then(res => {
    ElMessage.success('操作成功')
    emit('success')
    close()
  }).finally(() => {
    loadings.pay = false
  })
}

defineExpose({ open })
</script>